import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wanke/function.dart';
import 'user_page.dart';
import 'model/navigation_model.dart';
import 'device_page.dart';
import 'price_page.dart';
import 'monitor_page.dart';
import 'login_page.dart';
import 'util/event.dart';
import 'check_password.dart';
import 'dart:async';
import 'package:flutter/services.dart';
import 'package:flutter_jpush/flutter_jpush.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
class Index extends StatefulWidget {
  @override
  State<Index> createState() => new _IndexState();
}

class _IndexState extends State<Index> with TickerProviderStateMixin {
  Color mainColor = Colors.deepOrange;
  int _currentIndex = 0;
  List<NavigationModel> _navigationViews;
  bool isLogin = false;
  setTheme() {
    themeColor.then((color) {
      mainColor = color;
      setState(() {});
    });
  }

  initSafe() async {
    if (await getStorage("gesture") != null && await getStorage("finger") != null) {
      Navigator.of(context).push(
        new CupertinoPageRoute(builder: (context) {
          return new CheckPassword(mainColor, 3);
        }),
      );
    } else if (await getStorage("gesture") != null) {
      Navigator.of(context).push(
        new CupertinoPageRoute(builder: (context) {
          return new CheckPassword(mainColor, 2);
        }),
      );
    } else if (await getStorage("finger") != null) {
      Navigator.of(context).push(
        new CupertinoPageRoute(builder: (context) {
          return new CheckPassword(mainColor, 4);
        }),
      );
    }
  }

  void _startupJpush() async {
    await FlutterJPush.startup();
  }
  showPushNotice({String title,String content,Map extras}){
    if (extras != null) {
      print("有附加字段，弹窗");
      print(extras);
      var type = extras['type'];

      print(type);
      switch (type) {
        case "notice":
          showDialog<Null>(
            context: context,
            builder: (context) {
              return new AlertDialog(
                title: new Text(title ?? "消息提醒"),
                content: new Text(content ?? "无内容"),
                actions: <Widget>[
                  new FlatButton(
                    onPressed: () async {
                      Navigator.of(context).pop();
                    },
                    child: new Text(
                      '确定',
                    ),
                  ),
                ],
              );
            },
          );
          break;
        case "url":
          showDialog<Null>(
            context: context,
            builder: (context) {
              return new AlertDialog(
                title: new Text(title ?? "消息提醒"),
                content: new Text(content ?? "无内容"),
                actions: <Widget>[
                  new FlatButton(
                    onPressed: () async {
                      Navigator.of(context).pop();
                      launch(extras['url']);
                    },
                    child: new Text(
                      '查看',
                    ),
                  ),
                  new FlatButton(
                    onPressed: () async {
                      Navigator.of(context).pop();
                    },
                    child: new Text(
                      '取消',
                    ),
                  ),
                ],
              );
            },
          );

          break;
//        case "page":
//          showDialog<Null>(
//            context: context,
//            builder: (context) {
//              return new AlertDialog(
//                title: new Text(notification.title ?? "消息通知"),
//                content: new Text(notification.content ?? "无内容"),
//                actions: <Widget>[
//                  new FlatButton(
//                    onPressed: () {
//                      Navigator.of(context).pop();
//                      Navigator.of(context).push(
//                        new CupertinoPageRoute(builder: (context) {
//                          return new LoginPage(mainColor);
//                        }),
//                      );
//                    },
//                    child: new Text(
//                      '查看',
//                    ),
//                  ),
//                  new FlatButton(
//                    onPressed: () {
//                      Navigator.of(context).pop();
//                    },
//                    child: new Text(
//                      '取消',
//                    ),
//                  ),
//                ],
//              );
//            },
//          );
//          break;
        default:
          showDialog<Null>(
            context: context,
            builder: (context) {
              return new AlertDialog(
                title: new Text(title ?? "消息提醒"),
                content: new Text(content ?? "无内容"),
                actions: <Widget>[
                  new FlatButton(
                    onPressed: () async {
                      Navigator.of(context).pop();
                    },
                    child: new Text(
                      '确定',
                    ),
                  ),
                ],
              );
            },
          );
          break;
      }
    } else {
      print("无附加字段，弹窗");
      showDialog<Null>(
        context: context,
        builder: (context) {
          return new AlertDialog(
            title: new Text(title ?? "消息提醒"),
            content: new Text(content ?? "无内容"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () async {
                  Navigator.of(context).pop();
                },
                child: new Text(
                  '确定',
                ),
              ),
            ],
          );
        },
      );
    }
  }
  @override
  void initState() {
    super.initState();
    eventBus.on<Event>().listen((event) async {
      switch (event.msg) {
        case "theme":
          setTheme();
          break;
      }
    });
    _startupJpush();

    FlutterJPush.addConnectionChangeListener((bool connected) {
      if (connected) {
        FlutterJPush.getRegistrationID().then((String regId) {
          print("主动获取设备号:$regId");
          setStorage("jpushid", "$regId");
        });
      }
    });

    FlutterJPush.addnetworkDidLoginListener((String registrationId) {
      print("收到设备号:$registrationId");
      setStorage("jpushid", "$registrationId");
    });

    FlutterJPush.addReceiveNotificationListener(
          (JPushNotification notification) {
        if(Platform.isIOS){
          if(notification.appState==AppState.active){
            showPushNotice(title: notification.title,content:notification.content,extras:notification.extras);
          }
        }
        print("APP状态：${notification.appState}");
        print("收到推送提醒: $notification");
      },
    );
    // FlutterJPush.addReceiveCustomMsgListener((JPushMessage msg) {
    //   print("收到推送消息提醒: $msg");
    //   showPushNotice(title:msg.title,content:msg.message,extras:msg.extras);
    // });
    FlutterJPush.addReceiveOpenNotificationListener((JPushNotification notification) {
      showPushNotice(title: notification.title,content:notification.content,extras:notification.extras);
    });
    setTheme();
    initSafe();
    _navigationViews = <NavigationModel>[
      new NavigationModel(
        icon: new ImageIcon(AssetImage("images/wky.png")),
        title: new Text("设备"),
        vsync: this,
      ),
      new NavigationModel(
        icon: new ImageIcon(AssetImage(
          "images/price.png",
        )),
        title: new Text("行情"),
        vsync: this,
      ),
      new NavigationModel(
        icon: new ImageIcon(AssetImage("images/monitor.png")),
        title: new Text("监控"),
        vsync: this,
      ),
      new NavigationModel(
        icon: new Icon(Icons.perm_identity),
        title: new Text("我的"),
        vsync: this,
      ),
    ];
  }

  @override
  void dispose() {
    super.dispose();
    for (NavigationModel view in _navigationViews) {
      view.controller.dispose();
    }
  }

  Future<bool> willPop() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('退出玩客随行？'),
          actions: <Widget>[
            FlatButton(
              child: Text(
                '退出',
                style: new TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
              ),
              onPressed: () {
                Navigator.of(context).pop();
                SystemNavigator.pop();
              },
            ),
            FlatButton(
              child: Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
    return new Future.value(false);
  }

  @override
  Widget build(BuildContext context) {
    final BottomNavigationBar bottomNavigationBar = new BottomNavigationBar(
      items: _navigationViews.map((NavigationModel navigationIconView) => navigationIconView.item).toList(),
      currentIndex: _currentIndex,
      fixedColor: mainColor,
      type: BottomNavigationBarType.fixed,
      onTap: (int index) async {
        var uid = await getStorage("uid");
        if(index==1){
          eventBus.fire(new Event("price"));
          setState(() {
            _currentIndex = index;
          });
        }else if (index == 2) {
          if(uid==null){
            Navigator.of(context).push(
              new CupertinoPageRoute(builder: (context) {
                return new LoginPage(mainColor);
              }),
            ).then((value) async {
              if (value != null) {
                eventBus.fire(new Event("login"));
                eventBus.fire(new Event("monitor"));
                setState(() {
                  _currentIndex = index;
                });
              }
            });
          }else{
            eventBus.fire(new Event("monitor"));
            setState(() {
              _currentIndex = index;
            });
          }
        } else {
          setState(() {
            _currentIndex = index;
          });
        }
      },
    );

    return new WillPopScope(
        child: new Scaffold(
          body: new IndexedStack(
            children: <Widget>[
              new DevicePage(),
              new PricePage(),
              new MonitorPage(),
              new UserPage(),
            ],
            index: _currentIndex,
          ),
          bottomNavigationBar: bottomNavigationBar,
        ),
        onWillPop: willPop);
  }
}
